﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GamePlusClassLibrary;

namespace GamePlus.Master
{
    public partial class Gameplus : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            BlocosDeslogado(true);
            BlocosLogado(false);

            HttpCookie objCookie = LerCookie();
            if (objCookie != null)
            {
                BlocosDeslogado(false);
                BlocosLogado(true);

                lblNomeUsuario.InnerHtml = string.Empty;
                lblNomeUsuario.InnerHtml = objCookie["uname"].ToString();

                emMensagemPessoal.InnerHtml = string.Empty;
                emMensagemPessoal.InnerHtml = objCookie["msgpes"].ToString();
            }
        }

        private void BlocosLogado(bool bVisible)
        {
            divareausuario.Visible = bVisible;
            divmeusdados.Visible = bVisible;
            divsair.Visible = bVisible;
            divdigitemensagem.Visible = bVisible;
        }

        private void BlocosDeslogado(bool bVisible)
        {
            divcadastrese.Visible = bVisible;
            divlogin.Visible = bVisible;
        }

        protected void btnLogin_OnClick(object source, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtEmail.Text) && !string.IsNullOrEmpty(txtPassword.Text))
            {
                if (txtEmail.Text.IndexOf("@") > 0)
                {
                    Usuario objUsuario = Usuario.Carregar(txtEmail.Text, txtPassword.Text);
                    if (objUsuario != null)
                        CriarCookie(objUsuario);
                }
            }
        }


        public bool UsuarioLogado()
        {
            HttpCookie objCookie = LerCookie();
            if (objCookie != null)
            {
                if (objCookie.Expires >= DateTime.Now)
                    return true;
                else
                    return false;
            }
            else
                return false;
        }
        
        public HttpCookie LerCookie()
        {
            HttpCookie objCookie = null;
            if (Request.Cookies["gameplus"] != null)
                objCookie = Request.Cookies["gameplus"];
                     
            return objCookie;
        }

        public void CriarCookie(Usuario objUsuario)
        {
            HttpCookie objCookie = new HttpCookie("gameplus");
            objCookie["uid"] = objUsuario.Idf_Usuario.Value.ToString();
            objCookie["uname"] = objUsuario.Nme_Usuario;
            objCookie["msgpes"] = objUsuario.Des_Mensagem_Pessoal;
            objCookie.Expires = DateTime.Now.AddMinutes(1);
            Response.AppendCookie(objCookie);
        }
    }
}